import Vue from 'vue'
// 全局配置
import settings from './settings.js'
function computedBaseUrl(url) {
	// console.log(url);
	return (url.indexOf('http') === -1 ? settings.baseUrl : '') + url
}

// 发送请求
export default (options) => {
	const {
		url = '',
		method = 'GET',
		data = {},
		header = {}
	} = options
	return new Promise((resolve, reject) => {
			try {
				if (options.headers.isToken == true) {
					uni.request({
						url: computedBaseUrl(url),
						method,
						data,
						header: {
							// "Content-Type": "multipart/form-data",
							// "Token": uni.getStorageSync('token'),
							"Authorization": uni.getStorageSync('token'),
							// "Authorization" : 'Bearer ' + JSON.parse(uni.getStorageSync('token')), // 让每个请求携带自定义token 请根据实际情况自行修改
							...header
						},
						
						success(e) {
							if (e.data.code == 401) {
								uni.reLaunch({url: '/pages/login/login',});
							}
							resolve(e.data)
						},
						fail(e) {
							if (e.data.code == 401) {
								uni.reLaunch({url: '/pages/login/login',});
							}
							reject({...e,msg:e.errMsg||e.msg||'未知错误'})
						}
					})
				}else{
					uni.request({
						url: computedBaseUrl(url),
						method,
						data,
						header: {
							// "Content-Type": "multipart/form-data",
							// "Token": uni.getStorageSync('token'),
							// "Authorization": uni.getStorageSync('token'),
							// "Authorization" : 'Bearer ' + JSON.parse(uni.getStorageSync('token')), // 让每个请求携带自定义token 请根据实际情况自行修改
							...header
						},
						success(e) {
							if (e.data.code == 401) {
								uni.reLaunch({url: '/pages/login/index',});
							}
							resolve(e.data)
						},
						fail(e) {
							if (e.data.code == 401) {
								uni.reLaunch({url: '/pages/login/index',});
							}
							reject({...e,msg:e.errMsg||e.msg||'未知错误'})
						}
					})
				}
				
			} catch (err) {
				reject({...err,msg:err.errMsg||err.msg||'未知错误'})
			}
		}).then(data => data)
		.catch(err => [err, null])
}
